package tk.mybatis.springboot.wexin.service.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.springboot.api.controller.BaseController;
import tk.mybatis.springboot.share.util.WechatMediaUtil;
import tk.mybatis.springboot.share.util.WechatProcess;
import tk.mybatis.springboot.share.util.XmlUtil;
import tk.mybatis.springboot.wexin.bean.WeChatMessageBean;
import tk.mybatis.springboot.wexin.enums.WechatMessageTypeEnum;
import tk.mybatis.springboot.wexin.service.CoreService; 
@Service
public class CoreServiceImpl extends HttpServlet implements CoreService{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3553094321190952610L;
	
	@Autowired
	private WechatMessageServiceImpl wechatMessageService;
	
	@Override
	public void wexGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");  
  
        /** 读取接收到的xml消息 */  
        StringBuffer sb = new StringBuffer();  
        InputStream is = request.getInputStream();  
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");  
        BufferedReader br = new BufferedReader(isr);  
        String s = "";  
        while ((s = br.readLine()) != null) {  
            sb.append(s);  
        }  
        String xml = sb.toString(); //次即为接收到微信端发送过来的xml数据  
  
        String result = "";  
        /** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要把它直接返回 */  
        String echostr = request.getParameter("echostr");  
        if (echostr != null && echostr.length() > 1) {  
            result = echostr;  
        } else {  
            //正常的微信处理流程  
            result = WechatProcess.processWechatMag(xml);  
        }  
  
        try {  
            OutputStream os = response.getOutputStream();  
            os.write(result.getBytes("UTF-8"));  
            os.flush();  
            os.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
	/** 
     * 处理微信发来的请求 
     *  
     * @param request 
     * @return 
	 * @throws Exception 
     */ 
	@Override
    public String processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {  
    			String respXml = null;
    			// 调用parseXml方法解析请求消息
    			Map<String, String> requestMap = XmlUtil.parseXml(request);
    			if (requestMap.keySet().size() < 1) {
    				return BaseController.error("错误").toString();
    			}
    			System.out.println("微信发送的xml为：");
    			for (String key : requestMap.keySet()) {
    				System.out.println(key + "：" + requestMap.get(key));
    			}

    			// 发送方帐号
    			String fromUserName = requestMap.get("FromUserName");
    			// 开发者微信号
    			String toUserName = requestMap.get("ToUserName");
    			//消息创建时间
    			String createTime = requestMap.get("CreateTime");
    			Date create_date = new Date(Long.parseLong(createTime));
    			// 消息类型
    			String msgType = requestMap.get("MsgType");
    			//消息的id
    			String MsgId = requestMap.get("MsgId");

    			//转换格式
    			WechatMessageTypeEnum msg_type = WechatMessageTypeEnum.valueOf(msgType);
    			WeChatMessageBean weChatMessage = wechatMessageService.read(toUserName, fromUserName, create_date, msg_type, MsgId, requestMap);
      
    			if (null != weChatMessage) {
    				if (WechatMessageTypeEnum.text.equals(weChatMessage.getMsgType())) {
    					respXml = XmlUtil.textMessageToXml(weChatMessage);
    				} else {
    					respXml = WechatMediaUtil.toMessageByXml(weChatMessage);
    				}
    				System.out.println(respXml.toString());
    				return respXml;
    			}

    	return "success";
   
    }  
}
